package upc.controller;

import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import upc.constant.RedisKey;
import upc.controller.request.LoginRequest;
import upc.controller.request.RegisterRequest;
import upc.controller.request.SendCodeRequest;
import upc.service.AuthService;
import upc.util.CommonUtil;
import upc.util.JsonData;

@RestController
@RequestMapping("api/v1/auth")
public class AuthController {


    /**
     * 验证码过期时间
     */
    private static final long CAPTCHA_CODE_EXPIRED = 1000 * 10 *  60;

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AuthService authService;

    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "emotion-service:captcha:"+CommonUtil.MD5(ip+userAgent);
        return key;
    }


    /**
     * 发送短信验证码
     * @return
     */
    @PostMapping("register_captcha")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request){
        JsonData jsonData = authService.sendCode(sendCodeRequest);
        return jsonData;
    }


    /**
     * 会议发布者登陆
     * @param request
     * @return
     */
    @PostMapping("login")
    public JsonData login(@RequestBody LoginRequest request){
        JsonData jsonData = authService.login(request);
        return jsonData;
    }


    @PostMapping("register")
    public JsonData register(@RequestBody RegisterRequest pubRequest, HttpServletRequest request){
        JsonData jsonData;
        String key = String.format(RedisKey.CHECK_CODE_KEY,pubRequest.getPhone());;
        String code = redisTemplate.opsForValue().get(key);
        if(pubRequest.getCode().equals(code.substring(0,6))){
            jsonData = authService.register(pubRequest);
            redisTemplate.delete(key);
        }else{
            jsonData= JsonData.buildError("验证码错误");
        }

        return jsonData;
    }






}
